package com.schoolhelper.config;

import com.schoolhelper.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 1. 从请求头获取token
        String token = request.getHeader("Authorization");
        
        // 2. 验证token格式
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去除Bearer前缀
            
            // 3. 验证token有效性
            if (jwtUtils.validateToken(token)) {
                // 4. 解析token获取用户ID
                Long userId = jwtUtils.getUserIdFromToken(token);
                
                // 5. 将用户ID存入SecurityContext
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userId, null, null);
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        
        // 继续执行后续过滤器
        filterChain.doFilter(request, response);
    }
}